<template>
  <div class="forget-email">
    <div v-show="isEmailNext === 'first'">
      <el-form :model="forgetForm" ref="forgetForm" class="forget-form" :rules="rules">
        <el-form-item class="l-input" prop="loginName">
          <el-input :placeholder="$t('login.plahText')" type="text" v-model.trim="forgetForm.loginName">
            <template slot="prepend">{{$t('login.account')}}</template>
          </el-input>
        </el-form-item>
        <el-form-item class="l-input mobile-item" prop="email">
          <el-input :placeholder="$t('login.emailText')" type="text" v-model.trim="forgetForm.email">
            <template slot="prepend">{{$t('login.bindEmail')}}</template>
          </el-input>
          <span class="check-code" @click.stop="getCheckCode" :class="isCheckBtnDisable ? 'disabled' : ''">{{codeContent}}</span>
        </el-form-item>
        <el-form-item class="l-input code-item" :class="codeError ? 'code-item1' : ''">
          <el-input :placeholder="$t('login.codeText')" type="text" v-model.trim="forgetForm.authCode" @blur="blurCode">
            <template slot="prepend">{{$t('login.verificationCode')}}</template>
          </el-input>
          <span v-show="codeError" class="codeError">{{codeCont}}</span>
        </el-form-item>
        <div class="forget-form-btn">
          <el-button type="primary" @click.stop="emailNext" class="primary_btn next-btn">{{$t('login.next')}}</el-button>
        </div>
      </el-form>
    </div>
    <div v-show="isEmailNext === 'two'">
      <el-form :model="forgetForm1" ref="forgetForm1" class="forget-form" :rules="rules">
        <el-form-item class="l-input">
          <el-input :placeholder="$t('login.plahText')" type="text" v-model.trim="forgetForm1.loginName" disabled="disabled">
            <template slot="prepend">{{$t('login.account')}}</template>
          </el-input>
        </el-form-item>
        <el-form-item class="l-input" prop="password">
          <el-input :placeholder="$t('validate.enterPassword')" type="password" v-model.trim="forgetForm1.password">
            <template slot="prepend">{{$t('login.loginPassword')}}</template>
          </el-input>
        </el-form-item>
        <el-form-item class="l-input" prop="surePwd">
          <el-input :placeholder="$t('validate.enterPasswordAgain')" type="password" v-model.trim="forgetForm1.surePwd">
            <template slot="prepend">{{$t('login.surePwd')}}</template>
          </el-input>
        </el-form-item>
        <div style="text-align: center" class="forget-form-btn">
          <el-button @click.stop="cancelPhone" class="primary_btn">{{$t('public.reset')}}</el-button>
          <el-button type="primary" @click.stop="submitForm" class="primary_btn">{{$t('public.confirm')}}</el-button>
        </div>
      </el-form>
    </div>
    <div v-show="isEmailNext === 'three'" class="text-center phone--three">
      <div style="margin-top: 20px"><i class="iconfont icon-xuanzhong"></i></div>
      <div class="phone--three-conent">{{$t('login.phoneTipSuccess')}}</div>
      <div class="phone--three-btn forget-form-btn">
        <el-button type="primary" @click.stop="returnLogin" class="primary_btn">{{$t('login.reLogin')}}</el-button>
      </div>
    </div>
  </div>
</template>

<script>
  import {checkform} from '@/utils/validate'
  import * as m7Utils from '@/utils/m7Utils'
  let md5 = require('md5')
  export default {
    name: 'emailPwd',
    components: {
    },
    data () {
      let validate2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error(this.$t('validate.required')))
        } else if (checkform(value, 'Email')) {
          callback(new Error(this.$t('validate.email')))
        } else {
          callback()
        }
      }
      let validate3 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error(this.$t('validate.disagreePassword')))
        } else if (value !== this.forgetForm1.password) {
          callback(new Error(this.$t('validate.disagreePassword')))
        } else {
          callback()
        }
      }
      let validate4 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error(this.$t('validate.enterPassword')))
        } else if (!this.regexPass(value)) {
          callback(new Error(this.$t('validate.newPasswordRule')))
        } else {
          callback()
        }
      }
      return {
        codeCont: '',
        codeContent: this.$t('login.getCheckCode'),
        totalTime: 60,
        codeError: false,
        rules: {
          password: [
            { validator: validate4, trigger: 'blur' }
          ],
          surePwd: [
            { validator: validate3, trigger: 'blur' }
          ],
          email: [
            { validator: validate2, trigger: 'blur' }
          ],
          loginName: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ]
        },
        forgetForm: {
          loginName: '',
          authCode: '',
          email: ''
        },
        forgetForm1: {
          authKey: '',
          loginName: '',
          password: '',
          surePwd: ''
        },
        updatePwd: false,
        isCheckBtnDisable: false,
        codeKey: '',
        isEmailNext: 'first'
      }
    },
    props: {
    },
    computed: {
    },
    methods: {
      submitForm () {
        this.$refs.forgetForm1.validate((valid) => {
          if (valid) {
            console.log(this.forgetForm1)
            let _newKey = md5(m7Utils.Base64.encode(`${this.forgetForm1.authKey}m7${this.forgetForm1.loginName}`))
            const _data = {
              encrypt: true,
              loginName: this.forgetForm1.loginName,
              password: m7Utils.encrypt(_newKey.substr(0, 16), this.forgetForm1.password),
              authKey: this.forgetForm1.authKey
            }
            this.$store.dispatch('resetPassword', _data).then(res => {
              if (res.success) {
                this.isEmailNext = 'three'
              } else {
                if (res.message === 'unknow error!') {
                  this.$message.error(this.$t('message.unknown_err'))
                } else if (res.message === 'reset_password_timeout') {
                  this.isEmailNext = 'first'
                  this.$refs.forgetForm.resetFields()
                  this.$refs.forgetForm1.resetFields()
                  this.forgetForm = {
                    loginName: '',
                    authCode: '',
                    email: ''
                  }
                  this.forgetForm1 = {
                    authKey: '',
                    loginName: '',
                    password: '',
                    surePwd: ''
                  }
                  this.$emit('reForgetPanel')
                }
              }
            })
          }
        })
      },
      regexPass (passwordNew) {
        let regexPass = false
        let lengthRegex = new RegExp('^.{8,}$') // >= 8位
        let characterRegex = new RegExp('[a-z]') // 小寫
        let characterRegex2 = new RegExp('[A-Z]') // 大寫
        let numberRegex = new RegExp('[0-9]')// 數字
        let chinese = new RegExp('[\\u4E00-\\u9FFF]+', 'g') // 是否有中文
        let num = 0
        let temporary = this.forgetForm1.password
        temporary = temporary.replace(/[^0-9a-zA-Z]/g, '')
        if (characterRegex.test(passwordNew)) {
          num += 1
        }
        if (characterRegex2.test(passwordNew)) {
          num += 1
        }
        if (numberRegex.test(passwordNew)) {
          num += 1
        }
        if ((passwordNew.length - temporary.length) > 0) {
          num += 1
        }
        if (num >= 3) {
          regexPass = true
        } else {
          regexPass = false
        }
        if (!lengthRegex.test(passwordNew)) {
          regexPass = false
        }
        if (chinese.test(passwordNew)) {
          regexPass = false
        }
        let limitArr = ['%', '&', '"', '\'', '<', '>', '+']
        for (let i = 0; i < limitArr.length; i++) {
          if (passwordNew.indexOf(limitArr[i]) > -1) {
            regexPass = false
            break
          }
        }
        return regexPass
      },
      cancelPhone () {
        this.forgetForm1.password = ''
        this.forgetForm1.surePwd = ''
      },
      countDown () {
        // 这里解决60秒不见了的问题
        this.isCheckBtnDisable = true
        this.codeContent = this.totalTime + this.$t('login.refreshSend')
        let clock = window.setInterval(() => {
          this.totalTime--
          this.codeContent = this.totalTime + this.$t('login.refreshSend')
          // 当倒计时小于0时清除定时器
          if (this.totalTime < 0) {
            window.clearInterval(clock)
            this.isCheckBtnDisable = false
            this.codeContent = this.$t('login.getCheckCode')
            this.totalTime = 60
          }
        }, 1000)
      },
      emailNext () {
        this.$refs.forgetForm.validate((valid) => {
          if (valid) {
            const _data = {
              codeKey: this.codeKey,
              loginName: this.forgetForm.loginName,
              email: this.forgetForm.email,
              authCode: this.forgetForm.authCode
            }
            if (_data.codeKey === '') {
              if (window.localStorage.getItem('codeEmailKey')) {
                _data.codeKey = window.localStorage.getItem('codeEmailKey')
              }
            }
            let flag = this.blurCode()
            if (flag) {
              return false
            } else {
              this.codeError = false
            }
            this.$store.dispatch('checkAuthCode', _data).then(res => {
              if (res.success) {
                this.forgetForm1.loginName = this.forgetForm.loginName
                this.forgetForm1.authKey = res.authKey
                this.isEmailNext = 'two'
              }
            })
          }
        })
      },
      blurCode () {
        this.codeError = false
        if (!this.forgetForm.authCode || this.forgetForm.authCode === '') {
          this.codeError = true
          this.codeCont = this.$t('validate.required')
          return true
        }
        return false
      },
      getCheckCode (val) {
        this.$refs.forgetForm.validate((valid) => {
          if (valid) {
            // 如果获取验证码正处于倒计时阶段，不允许提交
            if (this.isCheckBtnDisable) {
              return false
            }
            const _data = {
              loginName: this.forgetForm.loginName,
              email: this.forgetForm.email
            }
            this.$store.dispatch('getCheckCode', _data).then(res => {
              if (res.success) {
                this.countDown()
                this.codeKey = res.codeKey
                window.localStorage.setItem('codeEmailKey', res.codeKey)
              }
            })
          }
        })
      },
      returnLogin () {
        this.$emit('returnLogin')
      }
    },
    watch: {
    },
    beforeMount () {}
  }
</script>
<style lang="stylus" scoped>
  @import "styl/forget.styl"
  @import "../../../assets/common.styl"
  .text-center
    text-align center
  .icon
    font-size 20px
    color #a6a6a6
  a
    color  $c-main
  .forget-email
    position relative
    .l-input
      width 317px
      margin 0px 110px
      margin-bottom 15px
      border-radius 22px
      display block
      border 0
      line-height 24px
      input
        background #c0DDEB
        border 0
        box-size(279px,42px)
    .icon-xuanzhong
      border-radius: 50%;
      padding: 8px;
      background-color: #5ec198;
      color: #fff;
    .forget-form-btn
      text-align center
      padding-top 20px
      padding-bottom 20px
      span
        border: 1px solid #a6a6a6;
        padding: 6px 20px;
        text-align: center;
        border-radius: 4px;
        color #a6a6a6
      span:hover
        border: 1px solid #459ae9;
        color: #459ae9;
        cursor pointer
    .mobile-item
      position relative
      .check-code
        top: 4px;
        position: absolute;
        left: 330px;
        min-width: 116px;
        text-align: center;
        border: 1px solid #459ae9;
        height: 30px;
        line-height: 30px;
        border-radius: 4px;
        color: #459ae9;
        cursor: pointer;
      .check-code:hover
        border: 1px solid #459ae9;
        color: #459ae9;
      .disabled
        color: #a6a6a6
        border: 1px solid #a6a6a6;
        cursor: not-allowed
      .disabled:hover
        color: #a6a6a6
        border: 1px solid #a6a6a6;
  .phone--three
    .phone--three-conent
      color #a6a6a6
      margin: 20px 70px 30px 70px
    .phone--three-btn
      text-align center
  .codeError
    color: rgb(245, 108, 108);
    font-size: 12px;
    position: absolute;
    left: 80px;
    top: 30px;
</style>
